import subprocess
import sys
import os

def run_script(script_path):
    """运行指定的Python脚本"""
    try:
        print(f"正在运行: {script_path}")
        print("=" * 50)
        
        # 使用subprocess运行脚本
        result = subprocess.run(
            [sys.executable, script_path],
            cwd=os.path.dirname(script_path),
            capture_output=False,
            text=True
        )
        
        if result.returncode == 0:
            print(f"\n{script_path} 运行成功！")
            print("=" * 50)
            return True
        else:
            print(f"\n{script_path} 运行失败，返回码: {result.returncode}")
            return False
            
    except Exception as e:
        print(f"运行 {script_path} 时出错: {e}")
        return False

def main():
    """主函数 - 依次运行两个脚本"""
    print("=== 自动化问答生成流程 ===")
    print("步骤1: 文档分段处理")
    print("步骤2: 问答对生成")
    print()
    
    # 定义脚本路径
    base_dir = r"d:\AAA\LLM_autoQA"
    word_segmenter_path = os.path.join(base_dir, "word_segmenter.py")
    autoqa_generator_path = os.path.join(base_dir, "autoQA_generator.py")
    
    # 检查文件是否存在
    if not os.path.exists(word_segmenter_path):
        print(f"错误: 找不到文件 {word_segmenter_path}")
        return
    
    if not os.path.exists(autoqa_generator_path):
        print(f"错误: 找不到文件 {autoqa_generator_path}")
        return
    
    # 步骤1: 运行文档分段器
    print("\n步骤1: 开始文档分段处理...")
    if not run_script(word_segmenter_path):
        print("文档分段处理失败，停止执行")
        return
    
    print("\n" + "=" * 60)
    
    # 步骤2: 运行问答生成器
    print("\n步骤2: 开始问答对生成...")
    if not run_script(autoqa_generator_path):
        print("问答对生成失败")
        return
    
    print("\n" + "=" * 60)
    print("\n请查看生成的文件:")
    print("- 分段文件: 分段文件/ 目录")
    print("- 问答对文件: qa_output_segments.xlsx")

if __name__ == "__main__":
    main()